package com.example.mybluetooth;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mybluetooth.adapter.BleScanAdapter;
import com.example.mybluetooth.bean.BleDevice;


import static com.example.mybluetooth.BleScanHelper.mBleDeviceList;
import static com.example.mybluetooth.BluetoothUtils.OpenBluetooth_Request_Code;

public class BleScanPageFragment extends Fragment {

    private final String[] permissionLists = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION };
    //RecyclerView设配器
    private BleScanAdapter mAdapter;
    //蓝牙扫描辅助类
    private BleScanHelper mBleScanHelper;
    //扫描时间
    private int mScanTime = 2000;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;

//构造函数
    public BleScanPageFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = LayoutInflater.from(getActivity()).inflate(
                R.layout.blescan_page_fragment, container, false);
        //需要先返回view  布局id才可不为空
        mSwipeRefreshLayout = view.findViewById(R.id.mSwipeRefreshLayout);
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        return view;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        初始化组件
        initView();
        //初始化蓝牙
        initBluetooth();
        //请求权限,并开始扫描
        startScan();
    }

//    初始化视图
    private void initView() {
        //初始化列表组件
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        mAdapter = new BleScanAdapter(this.getActivity());
        mRecyclerView.setAdapter(mAdapter);
//初始化下拉刷新布局
        mSwipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(this.getActivity(),R.color.colorPrimary ));
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
        //下拉屏幕的操作：先清空之前扫描到的设备，再通过适配器通知数据发生变化，最后再重新开始扫描。
                mBleDeviceList.clear();
                mAdapter.notifyDataSetChanged();
                //
                startScan();
            }
        });

    }
//    初始化蓝牙模块
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initBluetooth() {
        //初始化ble设配器
        //蓝牙设配器
        BluetoothManager bluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter mBluetoothAdapter = null;
        try {
            mBluetoothAdapter = bluetoothManager.getAdapter();
            Log.d("bluetoothManager的值为：",bluetoothManager.toString());
        } catch (Exception e) {
            System.out.println("获取蓝牙适配器时发生错误:"+e.getMessage());
            e.printStackTrace();
        }
        //判断蓝牙是否开启，如果关闭则请求打开蓝牙
//        以下该行由杨宁同学帮助修改得以运行 if (!mBluetoothAdapter.isEnabled()){，增加一个对象本身为空的判断更严谨
        Log.d("rickma","BleScanPageFragment对象，开始初始化蓝牙模块了，变量mBluetoothAdapter地址为："+ mBluetoothAdapter +"mBluetoothAdapter.isEnabled()结果为："+ mBluetoothAdapter.isEnabled());
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()){
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Log.d("通知activity","通知调用Fragment的Activity，蓝牙没有打开。");
            startActivityForResult(intent, OpenBluetooth_Request_Code);
        }
        //创建扫描辅助类，注意构造函数的权限声明和参数类型的不同，体会构造函数的调用差别
        mBleScanHelper = new BleScanHelper(getActivity());
        mBleScanHelper.setOnScanListener(new OnScanListener() {
            @Override
            public void onNext(BleDevice device) {
                //刷新ble设备列表
                Log.d("rickma","监听器onNext事件触发");
                Log.d("rickma：","实践领会到，理解匿名类内部的this关系，调用外部的类对象成员变量，就需要使用类名.this这种表达方式了。this:"+this.toString()+"，BleScanPageFragment.this="+BleScanPageFragment.this.toString());
                BleScanPageFragment.this.refreshBleDeviceList(device);
            }
            @Override
            public void onFinish() {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });

    }
    /**
     * 依据扫描结果刷新列表
     */
    private void refreshBleDeviceList(BleDevice mBleDevice) {
        Log.d("刷新蓝牙设备列表:","name = "+ mBleDevice.device.getName() + " ,address = "+mBleDevice.device.getAddress());

        for (int i=0; i< mBleDeviceList.size();i++) {
            //替换，只要mac地址相同，则更新该设备信息
            if (mBleDeviceList.get(i).device.getAddress().equals(mBleDevice.device.getAddress())){
                mBleDeviceList.set(i, mBleDevice);
                mAdapter.notifyItemChanged(i);
                return;
            }
        }
        //添加，刷新
        mBleDeviceList.add(mBleDevice);
        Log.d("rickma","扫描到的设备条数为："+mBleDeviceList.size());
        mAdapter.notifyItemChanged(mBleDeviceList.size() - 1);
    }
    /**
     * 请求蓝牙扫描权限并开始扫描
     */
    private void startScan() {
        Log.d("rickma","mBleScanHelper开始扫描了,该变量地址为："+mBleScanHelper.toString());
        //android 6.0 动态请求权限
        if (android.os.Build.VERSION.SDK_INT >= 23){
            if (BluetoothUtils.hasPermissions(getActivity(),permissionLists)){
//                有权限，开始扫描，否则请求权限
                mBleScanHelper.startScanBle(mScanTime);
            }else{
                //请求扫描权限
                requestPermissions(permissionLists,17);
            }
        }else{
            mBleScanHelper.startScanBle(mScanTime);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mBleScanHelper.startScanBle(mScanTime);
        }}

//        销毁BleScanHelper工具类
    @Override
    public void onDestroy() {
        super.onDestroy();
        mBleScanHelper.onDestroy();
    }
}

